package com.heima.sjms.单例模式.更高级单例;

import com.heima.sjms.单例模式.Student;

import java.io.*;
import java.lang.reflect.Constructor;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 陈辉
 * @data 2023 14:03
 */

public class Demo {
    private static Student stu;

    public static void main(String[] args) throws Exception {
        new Thread(()->{
            try {
                Student stu1 = getStu();
                System.out.println("stu1 = " + stu1);

                Class clazz = stu1.getClass();
                Constructor constructor = clazz.getDeclaredConstructor();
                constructor.setAccessible(true);
                stu1 = (Student) constructor.newInstance();
                System.out.println("stu1 = " + stu1);

                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day02_HashMap_ArrayList\\a.txt"));
                oos.writeObject(stu1);


                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day02_HashMap_ArrayList\\a.txt"));
                stu1 = (Student) ois.readObject();
                System.out.println("stu1 = " + stu1);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }).start();

        FutureTask task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Student stu2 = getStu();
                System.out.println("stu2 = " + stu2);
                return "ok";
            }
        });
        new Thread(task).start();

        Object ret = task.get();
        System.out.println("ret = " + ret);
    }

    public static Student getStu(){
        synchronized ("lock") {
            if (stu == null){
                try {
                    Thread.sleep(10);
                    Class<Student> studentClass = Student.class;
                    Constructor<Student> constructor = studentClass.getDeclaredConstructor();
                    constructor.setAccessible(true);
                    stu = constructor.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return stu;
    }


}
